import multiprocessing
import time

import cv2
import numpy as np

b_deal1 = 11
b_deal2 = 7
cr1 = 200
cr2 = 90
min_r = 100
max_r = 300
circle_color = (255, 255, 255)

font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1.5
font_color = (255, 255, 255)
line_thickness = 2
place = (20, 60)


class Circle_tool2:
    Text = "Distance:{:.0f}cm"
    # 距离接口
    distance = 164

    # 原图,二值图,灰图,处理后图像
    img = None
    b_img = None
    g_img = None
    d_img = None
    output_img = None
    x = 360
    y = 260
    r = 200

    deal_switch = False
    deal_Thread = None
    deal_mutex = 0

    def get_output(self):
        return self.output_img

    def deal_start(self):
        self.deal_switch = True
        if self.deal_Thread is None:
            self.deal_Thread = multiprocessing.Process(target=self.deal_img)
        self.deal_Thread.start()

    def deal_close(self):
        self.deal_switch = False

    def deal_img(self):
        while self.deal_switch:
            if self.deal_mutex == 0 or self.img is None:
                continue
            self.deal_mutex = 0
            self.img_deal()

    def img_deal(self):
        self.d_img = self.img
        self.g_b_deal()
        self.find_circle()
        self.draw_circle()

    def set_img(self, input_img):
        if input_img is not None:
            self.img = input_img
            self.deal_mutex = 1

    def g_b_deal(self):
        self.g_img = cv2.cvtColor(self.d_img, cv2.COLOR_BGR2GRAY)
        self.b_img = cv2.adaptiveThreshold(self.g_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, b_deal1,
                                           b_deal2)  # 自动阈值二值化

    def draw_circle(self):
        # return
        self.output_img = self.g_img
        if self.x >= 0 and self.y >= 0 and self.r >= 0:
            cv2.putText(self.output_img, self.Text.format(self.distance), place, font, font_scale, font_color,
                        line_thickness, cv2.LINE_AA)
            cv2.circle(self.output_img, (self.x, self.y), self.r, circle_color, 4)

    def find_circle(self):
        circles = cv2.HoughCircles(self.b_img, cv2.HOUGH_GRADIENT, 1, 170, param1=cr1, param2=cr2, minRadius=min_r,
                                   maxRadius=max_r)
        # if circles is not None:
        #     circles = np.round(circles[0, :]).astype("int")
        #     (x, y, r) = max(circles, key=lambda x: x[2])
        #     self.x = x
        #     self.y = y
        #     self.r = r


if __name__ == '__main__':
    tool = Circle_tool2()
    img = cv2.imread('2.png')
    tool.set_img(img)
    tool.img_deal()
    print(tool.y, tool.x, tool.r)
    cv2.imshow('show', tool.output_img)
    cv2.waitKey(0)
